package com.yzk.auction.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yzk.auction.entity.GoodsDTO;
import com.yzk.auction.entity.ResultInfo;
import com.yzk.auction.entity.ShowOrder;
import com.yzk.auction.entity.Users;
import com.yzk.auction.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Author: 园中葵小组成员
 * Description:登录注册控制器
 */
@WebServlet(name = "user",urlPatterns = "/user")
public class UserController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method.equals("login")){
            this.login(request,response);
        }else if(method.equals("showLogin")){
            this.showLogin(request,response);
        }else if(method.equals("register")){
            this.register(request,response);
        }else if(method.equals("showRegister")){
            this.showRegister(request,response);
        }else if(method.equals("success")){
            this.loginSuccess(request,response);
        }else if(method.equals("showInformation")){
            this.showInformation(request,response);
        }else if(method.equals("showUpdateInfo")){
            this.showUpdateInfo(request,response);
        }else if(method.equals("exit")){
            this.exit(request,response);
        }else if(method.equals("updateInfo")){
            this.updateInfo(request,response);
        }
    }

    /**
     * 登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //验证码校验
        String check = request.getParameter("check");
        //从session中获取验证码
        HttpSession session = request.getSession();
        String checkcode_server=(String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//为了保证验证码只能使用一次
        //区分大小写比较
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //验证码错误
            ResultInfo info = new ResultInfo();
            //注册失败
            info.setFlag(false);
            info.setErrorMsg("验证码错误");
            //将info对象序列化为json对象
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(info);
            //将json数据写回客户端
            //设置content-type
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        //获取手机号和密码
        String telephone = request.getParameter("telephone");
        String password = request.getParameter("password");
        //System.out.println(telephone);
        //System.out.println(password);
        //封装User对象
        Users users = new Users();
        users.setUser_tel(telephone);
        users.setUser_pwd(password);
        //调用Service查询
        UserService userService = new UserService();
        Users u = userService.login(users);

        ResultInfo info = new ResultInfo();

        //判断用户对象是否为null
        if(u == null) {
            //用户名密码错误
            info.setFlag(false);
            info.setErrorMsg("用户名或密码错误");
        }else{
            //登录成功
            info.setFlag(true);
        }
        //响应数据
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),info);
    }

    /**
     * 注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void register(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //验证码校验
        String check = request.getParameter("check");
        //从session中获取验证码
        HttpSession session = request.getSession();
        String checkcode_server=(String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//为了保证验证码只能使用一次
        //区分大小写比较
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //验证码错误
            ResultInfo info = new ResultInfo();
            //注册失败
            info.setFlag(false);
            info.setErrorMsg("验证码错误");
            //将info对象序列化为json对象
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(info);
            //将json数据写回客户端
            //设置content-type
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        //1.获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String telephone = request.getParameter("telephone");
        String sex = request.getParameter("sex");
        //2.封装对象
        Users users = new Users();
        users.setUser_name(username);
        users.setUser_pwd(password);
        users.setUser_tel(telephone);
        users.setUser_sex(sex);
        //3.调用service完成注册
        UserService userService = new UserService();
        boolean flag = userService.regist(users);
        ResultInfo info = new ResultInfo();
        //4.响应结果
        if(flag){
            //注册成功
            info.setFlag(true);
        }else{
            //注册失败
            info.setFlag(false);
            info.setErrorMsg("注册失败");
        }
        //将info对象序列化为json对象
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(info);
        //将json数据写回客户端
        //设置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    /**
     * 显示登录页面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showLogin(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/login.html").forward(request,response);
    }

    /**
     * 显示注册页面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showRegister(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/register.html").forward(request,response);
    }

    /**
     * 登录成功
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void loginSuccess(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String telephone = request.getParameter("telephone");
        UserService userService = new UserService();
        Users users = userService.findByTel(telephone);
        request.getServletContext().setAttribute("userList",users);
        if(users.getUser_name().equals("1008611") && users.getUser_pwd().equals("11111111"))
        {
            request.getRequestDispatcher("/management.jsp").forward(request,response);
        }else {
            request.getRequestDispatcher("/homepage.jsp").forward(request, response);
        }
    }

    /**
     * 显示个人信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showInformation(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //Users users = (Users) request.getServletContext().getAttribute("userList");
        //System.out.println( users.getUser_id());
        if(request.getParameter("id")!=null) {
            Integer uid = Integer.parseInt(request.getParameter("id"));
            UserService userService = new UserService();
            List<ShowOrder> list = userService.findOrderById(uid);
            request.getServletContext().setAttribute("showOrder", list);
        }
        request.getRequestDispatcher("WEB-INF/jsp/information.jsp").forward(request,response);
    }

    /**
     * 显示更新页面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showUpdateInfo(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("WEB-INF/jsp/updateInfo.jsp").forward(request,response);
    }

    /**
     * 更新个人信息
     * @param request
     * @param response
     */
    private void updateInfo(HttpServletRequest request,HttpServletResponse response){
        int isPictureModified = 0;
        //1.初始化FileUpload组件
        FileItemFactory factory = new DiskFileItemFactory();
        /**
         * FileItemFactory用于将前端表单的数据转换为一个个FileItem对象
         * ServletFileUpload则是为FileUpload组件提供Java Web的Http请求解析
         */
        ServletFileUpload sf = new ServletFileUpload(factory);
        //2.遍历所有FileItem
        try {
            List<FileItem> formData = sf.parseRequest(request);
            Users users = new Users();
            for(FileItem fi:formData) {
                if(fi.isFormField()) {
                    //System.out.println("普通输入项："+fi.getFieldName()+":"+fi.getString("UTF-8"));
                    switch (fi.getFieldName()) {
                        case "user_name":
                            users.setUser_name(fi.getString("UTF-8"));
                            break;
                        case "user_sex":
                            users.setUser_sex(fi.getString("UTF-8"));
                            break;
                        case "user_tel":
                            users.setUser_tel(fi.getString("UTF-8"));
                            break;
                        case "user_addr":
                            users.setUser_addr(fi.getString("UTF-8"));
                            break;
                        case "user_id":
                            users.setUser_id(Integer.parseInt(fi.getString("UTF-8")));
                            break;
                        case "isPictureModified":
                            isPictureModified = Integer.parseInt(fi.getString("UTF-8"));
                            break;
                        default:
                            break;
                    }
                }else {
                    if(isPictureModified == 1) {
                        //System.out.println("文件上传项："+fi.getFieldName());
                        //3.文件保存到服务器目录
                        String path = request.getServletContext().getRealPath("/upload");//获取Tomcat在实际运行环境下对应的目录的物理地址
                        //System.out.println("文件上传目录："+path);
                        //String fileName = "test.jpg";
                        //UUID根据计算机的本地特性生生成唯一的字符串
                        String fileName = UUID.randomUUID().toString();
                        //扩展名：
                        //fi.getName()得到原始文件名，截取最后一个.后所有字符串，例如wxml.jpg->.jpg
                        String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
                        fi.write(new File(path,fileName + suffix));
                        users.setUser_head("/upload/" + fileName + suffix);
                    }
                }
            }
            UserService userService = new UserService();
            int num = userService.update(users,isPictureModified);
            if(num == 1){
                Users u = userService.findById(users.getUser_id());
                request.getServletContext().removeAttribute("userList");
                request.getServletContext().setAttribute("userList",u);
            }
            response.sendRedirect("/user?method=showInformation");//返回列表页
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 用户退出
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void exit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getServletContext().removeAttribute("userList");
        request.getRequestDispatcher("/homepage.jsp").forward(request,response);
    }
}
